<template>
  <el-dialog v-dialogDrag :visible.sync="dialogVisible" :title="title" width="750px" @close="resetForm('ruleForm')">
    <button-group ref="buttonGroup" @deleteCancel="deleteCancel" @submitForm="submitForm('ruleForm')" @cancel="dialogVisible = false" />
    <div class="formTopFont">付款清单</div>
    <el-row>
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="auto">
        <el-row>
          <el-col :span="12">
            <el-form-item label="付款编号" prop="paymentNo">
              <el-input v-model="ruleForm.paymentNo" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货单号" prop="paymentId">
              <el-select v-model="ruleForm.receiptId" :disabled="title === '编辑'" style="width: 100%" @change="receipChange">
                <el-option v-for="item in receipList" :key="item.receiptId" :label="item.receiptNo" :value="item.receiptId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="付款日期" prop="paymentDate">
              <el-date-picker v-model="ruleForm.paymentDate" type="date" placeholder="选择日期" style="width: 100%" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供方名称" prop="supplierName">
              <el-input v-model="ruleForm.supplierName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="币种" prop="currency">
              <el-input v-model="ruleForm.currency" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总计付款金额" prop="paymentPrice">
              <el-input-number v-model="ruleForm.paymentPrice" style="width: 100%" disabled :precision="2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="本次付款金额" prop="thisPrice">
              <el-input-number v-model="ruleForm.thisPrice" :disabled="title === '编辑' || !ruleForm.receiptId" style="width: 100%" :max="9999999999" :precision="2" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已清金额" prop="clearPrices">
              <el-input-number v-model="clearPrices" disabled style="width: 100%" :precision="2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="待清金额" prop="unClearPrice">
              <el-input-number v-model="ruleForm.unClearPrice" disabled style="width: 100%" :precision="2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款类型" prop="type">
              <el-select v-model="ruleForm.type" style="width: 100%">
                <el-option label="付提货款" value="付提货款" />
                <el-option label="预付款" value="预付款" />
                <el-option label="应付尾款" value="应付尾款" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" maxlength="200" type="textarea" rows="3" show-word-limit />
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </el-dialog>
</template>
<script>
export default {
  props: {},
  data() {
    const checkPaymentNo = async (rule, value, callback) => {
      const res = await this.$axios.get(
        `/purchase/payment/verifyUnique?paymentNo=${value}&id=${
          this.ruleForm.id || ''
        }`
      )
      if (res?.data.code === 200) {
        return res.data.data
          ? callback()
          : new Error(callback('付款编号重复！'))
      } else {
        return new Error(callback(res.data.msg))
      }
    }
    return {
      clearPrices: '',
      receipList: [],
      title: '',
      ruleForm: {
        clearPrices: '',
        thisPrice: '',
        receiptNo: '',
        receiptId: '',
        supplierId: '',
        supplierName: '', // 供方名称
        paymentNo: '',
        clearPrice: '',
        paymentPrice: '',
        type: '',
        unClearPrice: '',
        currency: '',
        remark: '',
        paymentDate: ''
      },
      rules: {
        receiptId: [
          { required: true, message: '收款单号不能为空！', trigger: 'change' }
        ],
        paymentNo: [
          { required: true, message: '付款编号不能为空！', trigger: 'blur' },
          { validator: checkPaymentNo, trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      obj: {}
    }
  },
  watch: {
    ruleForm: {
      deep: true,
      handler(row) {
        if (this.title === '新增') {
          //已清金额 = 已清金额+本次付款金额(保存的时候监听计算的数据不可重复赋值否则会叠加值)
          this.clearPrices = +row.clearPrices + +row.thisPrice
          //待清金额 = 总计付款金额-已清金额
          row.unClearPrice = +row.paymentPrice - +this.clearPrices
        }
      }
    }
  },
  mounted() {},
  methods: {
    /**
     * @description: 新增编辑
     * @param {*} row
     * @return {*}
     */
    async showDialog(row) {
      this.obj = row
      await this.getReceipList(row.id || '')
      if (row && row.hasOwnProperty('id')) {
        this.title = '编辑'
        this.ruleForm = { ...this.ruleForm, ...row }
        this.ruleForm.clearPrices = this.ruleForm.clearPrice
        this.clearPrices = this.ruleForm.clearPrice
      } else {
        this.title = '新增'
      }
      this.dialogVisible = true
    },
    /* 获取所有收货单 */
    async getReceipList(id) {
      const res = await this.$axios.get(`/purchase/payment/search?id=${id}`)
      if (res?.data.code === 200) {
        this.receipList = res.data.data
      }
    },
    receipChange($event) {
      this.ruleForm.thisPrice = ''
      const obj = this.receipList.find((el) => el.receiptId === $event)
      this.ruleForm = { ...this.ruleForm, ...obj }
      this.ruleForm.clearPrices = this.ruleForm.clearPrice
      this.clearPrices = this.ruleForm.clearPrice
    },
    async deleteCancel() {
      if (this.title === '编辑') {
        this.$confirm(`确认删除数据？`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$axios
              .delete(`/purchase/payment/remove/${this.obj.id}`)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$notify.success('删除成功！')
                  this.dialogVisible = false
                  this.$emit('getTableInfo', 1)
                } else {
                  this.$notify.error(res.data.msg)
                }
              })
          })
          .catch(() => {})
      }
    },
    /**
     * @description: 表单提交
     * @param {*} formName
     * @return {*}
     */
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.ruleForm.clearPrice = this.clearPrices
          // console.log(this.ruleForm)
          const res = await this.$axios.post(
            '/purchase/payment/save',
            this.ruleForm
          )
          if (res?.data.code === 200) {
            this.$notify.success('提交成功！')
            this.dialogVisible = false
            this.$emit('getTableInfo')
          } else {
            this.$notify.error(res.data.msg)
          }
        }
      })
    },
    /**
     * @description: 重置表单
     * @param {*} formName
     * @return {*}
     */
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.ruleForm = Object.assign({}, this.$options.data.call(this).ruleForm)
    }
  }
}
</script>
<style lang='scss' scoped>
</style>
